<template>
  <div class="common-layout linear-gradient">
    <el-container>
      <el-header class="header-container">
        <div class="headerTitle">轧制精度仿真报告</div>
        <div class="aprd-search-container">
          <el-form :inline="true" :model="searchForm" class="aprd-search-form">
            <el-form-item label="钢种分档">
              <el-input v-model="searchForm.ypClass" placeholder="请输入" style="width:100px" size="small" />
            </el-form-item>
            <el-form-item label="宽度分档">
              <el-input v-model="searchForm.widthClass" placeholder="请输入" style="width:100px" size="small" />
            </el-form-item>
            <el-form-item label="厚度分档">
              <el-input v-model="searchForm.thicknessClass" placeholder="请输入" style="width:100px" size="small" />
            </el-form-item>
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="searchForm.startDate"
                type="datetime"
                placeholder="选择开始时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width:180px"
                size="small"
              />
            </el-form-item>
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="searchForm.endDate"
                type="datetime"
                placeholder="选择结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width:180px"
                size="small"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch" size="small">查询</el-button>
              <el-button @click="handleReset" size="small">重置</el-button>
              <el-button type="success" @click="handleExport" size="small">导出</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-header>
      <el-main>
        <!-- 两个列表并排显示 -->
        <div class="tables-container">
          <!-- 钢种信息列表 -->
          <div class="steel-grade-container">
            <div class="section-title">钢种信息</div>
            <div class="table-container-main">
              <el-table :data="steelGradeData"
                :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }" height="500" max-height="500">
                <el-table-column prop="ypIndex" label="钢种组" width="70">
                  <template #default="scope">{{ scope.row.ypIndex }}</template>
                </el-table-column>
                <el-table-column prop="steelGrade" label="钢牌号" width="90">
                  <template #default="scope">{{ scope.row.steelGrade }}</template>
                </el-table-column>
                <el-table-column prop="yp" label="屈服强度" width="90">
                  <template #default="scope">{{ Math.round(scope.row.yp) }}</template>
                </el-table-column>
              </el-table>
            </div>
          </div>

          <!-- 精度统计列表 -->
          <div class="accuracy-container">
            <div class="section-title">精度统计</div>
            <div class="table-container-main">
              <el-table :data="processedAccuracyData"
                :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }" style="cursor: pointer;" :span-method="accuracySpanMethod"
                @row-click="handleAccuracyRowClick" height="500" max-height="500">
                <el-table-column prop="ypIndex" label="钢种分档" width="90" />
                <el-table-column prop="widIndex" label="宽度分档" width="90" />
                <el-table-column prop="thkIndex" label="厚度分档" width="90" />
                <el-table-column prop="type" label="" width="170" />
                <el-table-column label="不同品规模型精度数据+/-10%偏差：（计算轧制力-实际轧制力）/计算轧制力" align="center">
                  <el-table-column prop="S1" label="S1" width="100" />
                  <el-table-column prop="S2" label="S2" width="100" />
                  <el-table-column prop="S3" label="S3" width="100" />
                  <el-table-column prop="S4" label="S4" width="100" />
                  <el-table-column prop="S5" label="S5" width="100" />
                </el-table-column>
                <el-table-column label="ZP=ROLL_FORCE_CALC/ACT" align="center">
                  <el-table-column prop="ZP1" label="ZP1" width="100" />
                  <el-table-column prop="ZP2" label="ZP2" width="100" />
                  <el-table-column prop="ZP3" label="ZP3" width="100" />
                  <el-table-column prop="ZP4" label="ZP4" width="100" />
                  <el-table-column prop="ZP5" label="ZP5" width="100" />
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
        <!-- 去掉分页组件 -->
        <!-- ZP图表弹窗 -->
        <el-dialog v-model="dialogVisible"
          :title="`ZP：${selectedRow?.ypIndex ?? ''}-${selectedRow?.widIndex ?? ''}-${selectedRow?.thkIndex ?? ''}`"
          width="80%" :close-on-click-modal="false" :destroy-on-close="true" @closed="handleDialogClose">
          <div class="chart-container">
            <div ref="zpChartRef" style="width: 100%; height: 500px;"></div>
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">关闭</el-button>
            </span>
          </template>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { rollingSimulationApi } from '/@/api/RollingSimulation/index';
import '/@/views/RollingSimulation/rollingSimulationModelCommonStyle.less';
import * as echarts from 'echarts';
import axios from 'axios';

const searchForm = reactive({
  ypClass: '',
  widthClass: '',
  thicknessClass: '',
  startDate: '',
  endDate: '',
});

const tableData = ref<any[]>([]);
const steelGradeData = ref<any[]>([]);
// 去掉分页相关数据

function formatNum(val: any) {
  if (val === null || val === undefined) return '-';
  if (typeof val === 'number') return val.toFixed(2);
  return val;
}

function formatPercentage(d: number, t: number) {
  if (t === 0) return '0%';
  const percentage = (d / t) * 100;
  return `${percentage.toFixed(2)}%`;
}

function formatDateForApi(val: string) {
  if (!val) return undefined;
  // 转为 yyyy-MM-dd-HH.mm.ss.SSSSSS
  const d = new Date(val);
  const pad = (n: number, l = 2) => n.toString().padStart(l, '0');
  const ms = pad(d.getMilliseconds(), 6); // 6位
  return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}-${pad(d.getHours())}.${pad(d.getMinutes())}.${pad(d.getSeconds())}.${ms}`;
}

// 获取钢种信息数据
const fetchSteelGradeData = async () => {
  try {
    const params = {
      pageIndex: 1, // 固定为1，因为只获取一次
      pageSize: 1000 // 获取所有数据
    };
    console.log('调用findByYpClass接口，参数:', params);
    const res = await rollingSimulationApi.findByYpClass(params);
    console.log('findByYpClass接口返回数据:', res);

    if (res && res.data && Array.isArray(res.data.data)) {
      steelGradeData.value = res.data.data;
      console.log('钢种数据:', steelGradeData.value);
    } else {
      steelGradeData.value = [];
      console.log('没有钢种数据返回');
    }
  } catch (error: any) {
    console.error('获取钢种数据失败:', error);
    steelGradeData.value = [];
  }
};

const allData = ref<any[]>([]);
const fetchTableData = async () => {
  try {
    console.log('开始获取表格数据...'); // 添加调试日志
    const params: any = {
      ypClass: searchForm.ypClass || undefined,
      widthClass: searchForm.widthClass || undefined,
      thicknessClass: searchForm.thicknessClass || undefined,
      pageIndex: 1, // 固定为1，因为只获取一次
      pageSize: 1000, // 获取所有数据
      startDate: formatDateForApi(searchForm.startDate),
      endDate: formatDateForApi(searchForm.endDate),
    };
    Object.keys(params).forEach(key => {
      if (params[key] === undefined) delete params[key];
    });
    console.log('请求参数:', params); // 添加调试日志

    const res = await rollingSimulationApi.classStatistics(params);
    console.log('接口返回结果:', res); // 添加调试日志

    if (res && res.data && Array.isArray(res.data.data)) {
      tableData.value = res.data.data;
      // pagination.total = res.data.count || res.data.data.length; // 不再使用本地分页
      console.log('表格数据:', tableData.value); // 添加调试日志
      console.log('数据条数:', tableData.value.length); // 添加调试日志
      // console.log('总条数:', pagination.total); // 添加调试日志
    } else {
      tableData.value = [];
      // pagination.total = 0; // 不再使用本地分页
      console.log('没有数据返回'); // 添加调试日志
    }
  } catch (e: any) {
    console.error('获取数据失败:', e); // 添加调试日志
    ElMessage.error(e?.msg || e?.message || '查询失败');
    tableData.value = [];
    // pagination.total = 0; // 不再使用本地分页
  }
};

function handleSearch() {
  // pagination.currentPage = 1; // 不再使用本地分页
  fetchSteelGradeData();
  fetchTableData();
}

function handleReset() {
  searchForm.ypClass = '';
  searchForm.widthClass = '';
  searchForm.thicknessClass = '';
  searchForm.startDate = '';
  searchForm.endDate = '';
  // pagination.currentPage = 1; // 不再使用本地分页
  fetchSteelGradeData();
  fetchTableData();
}

// 导出功能
const handleExport = async () => {
  try {
    // 构建参数对象，所有参数都传递
    const params: any = {
      ypClass: searchForm.ypClass && searchForm.ypClass.trim() ? searchForm.ypClass.trim() : '0',
      widthClass: searchForm.widthClass && searchForm.widthClass.trim() ? searchForm.widthClass.trim() : '0',
      thicknessClass: searchForm.thicknessClass && searchForm.thicknessClass.trim() ? searchForm.thicknessClass.trim() : '0',
      startDate: formatDateForApi(searchForm.startDate) || '',
      endDate: formatDateForApi(searchForm.endDate) || ''
    };

    console.log('导出参数:', params);
    console.log('原始日期值:', { startDate: searchForm.startDate, endDate: searchForm.endDate });

    // 调用导出接口
    const response = await axios.get('http://10.171.7.135:8080/coldbigdata/optimize/acidRolling/classStatistics/export', {
      params: params,
      responseType: 'blob', // 设置响应类型为blob以处理文件下载
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/octet-stream'
      }
    });

    console.log('导出响应状态:', response.status);
    console.log('导出响应头:', response.headers);

    // 创建下载链接
    const blob = new Blob([response.data]);
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    
    // 设置文件名（从响应头获取或使用默认名称）
    const contentDisposition = response.headers['content-disposition'];
    let filename = '轧制精度仿真报告.xlsx';
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
      if (filenameMatch && filenameMatch[1]) {
        filename = filenameMatch[1].replace(/['"]/g, '');
      }
    }
    
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    ElMessage.success('导出成功');
  } catch (error: any) {
    console.error('导出失败:', error);
    console.error('错误详情:', {
      message: error?.message,
      response: error?.response?.data,
      status: error?.response?.status
    });
    
    // 如果axios请求失败，尝试使用window.open方式
    try {
      // 构建参数对象，所有参数都传递
      const params: any = {
        ypClass: searchForm.ypClass && searchForm.ypClass.trim() ? searchForm.ypClass.trim() : '0',
        widthClass: searchForm.widthClass && searchForm.widthClass.trim() ? searchForm.widthClass.trim() : '0',
        thicknessClass: searchForm.thicknessClass && searchForm.thicknessClass.trim() ? searchForm.thicknessClass.trim() : '0',
        startDate: formatDateForApi(searchForm.startDate) || '',
        endDate: formatDateForApi(searchForm.endDate) || ''
      };
      
      let url = 'http://10.171.7.135:8080/coldbigdata/optimize/acidRolling/classStatistics/export';
      
      const queryString = Object.entries(params)
        .map(([key, value]) => `${key}=${encodeURIComponent(String(value))}`)
        .join('&');
      url += `?${queryString}`;
      
      console.log('备用下载URL:', url);
      
      window.open(url, '_blank');
      ElMessage.success('已在新窗口打开下载链接');
    } catch (fallbackError) {
      console.error('备用下载也失败:', fallbackError);
      ElMessage.error('导出失败，请检查网络连接');
    }
  }
};

// 弹窗相关数据
const dialogVisible = ref(false);
const selectedRow = ref<any>(null);
const zpChartRef = ref<HTMLElement>();
let zpChart: echarts.ECharts | null = null;

// 处理行点击事件
const handleRowClick = async (rowOrParams: any) => {
  // rowOrParams 可能是 row 或 params
  let params;
  let selectedRowData;
  
  if ('ypIndex' in rowOrParams && 'widIndex' in rowOrParams && 'thkIndex' in rowOrParams) {
    // 来自 handleAccuracyRowClick，直接使用传递的参数
    params = {
      ypClass: rowOrParams.ypIndex,
      widthClass: rowOrParams.widIndex,
      thicknessClass: rowOrParams.thkIndex,
      startDate: formatDateForApi(searchForm.startDate),
      endDate: formatDateForApi(searchForm.endDate)
    };
    selectedRowData = rowOrParams; // 保存原始行数据用于显示
  } else {
    // 来自其他地方，使用传递的参数
    params = rowOrParams;
    selectedRowData = rowOrParams;
  }

  console.log('点击行数据:', params); // 添加调试日志

  // 先显示弹窗
  selectedRow.value = selectedRowData;
  dialogVisible.value = true;

  // 等待弹窗打开
  await nextTick();

  try {
    // 这里用当前行的分档号（index字段）
    console.log("row", params)

    const res = await rollingSimulationApi.simulationReport(params);

    if (res && res.data && Array.isArray(res.data.data)) {
      initZpChart(res.data.data);
    } else {
      ElMessage.warning('未查询到相关数据');
    }
  } catch (error: any) {
    console.error('错误:', error); // 添加调试日志
    ElMessage.error(error?.msg || error?.message || '查询失败');
  }
};

// 初始化ZP图表
const initZpChart = (data: any[]) => {
  if (!zpChartRef.value) return;

  // 销毁之前的图表实例
  if (zpChart) {
    zpChart.dispose();
  }

  // 创建新的图表实例
  zpChart = echarts.init(zpChartRef.value);

  // 准备数据
  const xAxisData = ['zp1', 'zp2', 'zp3', 'zp4', 'zp5'];
  const series = data.map((item, index) => ({
    name: item.coilNo || `数据${index + 1}`,
    type: 'line',
    data: [
      item.zp1 || 0,
      item.zp2 || 0,
      item.zp3 || 0,
      item.zp4 || 0,
      item.zp5 || 0
    ],
    smooth: true,
    symbol: 'circle',
    symbolSize: 6,
    lineStyle: {
      width: 2
    }
  }));

  // 图表配置
  const option = {
    title: {
      text: `ZP：${selectedRow.value?.ypIndex ?? ''}-${selectedRow.value?.widIndex ?? ''}-${selectedRow.value?.thkIndex ?? ''}`,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: series.map(s => s.name),
      type: 'scroll',
      bottom: 10,
      textStyle: {
        fontSize: 12
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLabel: {
        fontSize: 12
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: 12,
        formatter: function (value: number) {
          return value.toFixed(2);
        }
      }
    },
    series: series
  };

  // 设置图表配置
  zpChart.setOption(option);

  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    zpChart?.resize();
  });
};

const processedAccuracyData = computed(() => {
  // 将每条数据拆成3条，分别为 >10%、总计、比例（去掉 <10%）
  const result: any[] = [];
  tableData.value.forEach(row => {
    result.push({
      ...row,
      type: '< -10%卷数',
      S1: row.diffxf1,
      S2: row.diffxf2,
      S3: row.diffxf3,
      S4: row.diffxf4,
      S5: row.diffxf5,
      ZP1: 0,
      ZP2: 0,
      ZP3: 0,
      ZP4: 0,
      ZP5: 0,
    });
    result.push({
      ...row,
      type: '> +10%卷数',
      S1: row.diffd1,
      S2: row.diffd2,
      S3: row.diffd3,
      S4: row.diffd4,
      S5: row.diffd5,
      ZP1: row.zpd1,
      ZP2: row.zpd2,
      ZP3: row.zpd3,
      ZP4: row.zpd4,
      ZP5: row.zpd5,
    });
    result.push({
      ...row,
      type: '总卷数',
      S1: row.difft1,
      S2: row.difft2,
      S3: row.difft3,
      S4: row.difft4,
      S5: row.difft5,
      ZP1: row.zpt1,
      ZP2: row.zpt2,
      ZP3: row.zpt3,
      ZP4: row.zpt4,
      ZP5: row.zpt5,
    });
    result.push({
      ...row,
      type: '[-10%,10%]占比',
      S1: formatPercentage(row.diffx1, row.difft1),
      S2: formatPercentage(row.diffx2, row.difft2),
      S3: formatPercentage(row.diffx3, row.difft3),
      S4: formatPercentage(row.diffx4, row.difft4),
      S5: formatPercentage(row.diffx5, row.difft5),
      ZP1: formatPercentage(row.zpx1, row.zpt1),
      ZP2: formatPercentage(row.zpx2, row.zpt2),
      ZP3: formatPercentage(row.zpx3, row.zpt3),
      ZP4: formatPercentage(row.zpx4, row.zpt4),
      ZP5: formatPercentage(row.zpx5, row.zpt5),
    });
  });
  return result;
});

// 精度统计表格合并单元格
const accuracySpanMethod = ({ rowIndex, columnIndex }: { rowIndex: number, columnIndex: number }) => {
  // 前三列合并，每3行为一组（去掉 <10% 后）
  if (columnIndex >= 0 && columnIndex <= 2) {
    if (rowIndex % 4 === 0) {
      return { rowspan: 4, colspan: 1 };
    } else {
      return { rowspan: 0, colspan: 0 };
    }
  }
  return { rowspan: 1, colspan: 1 };
};

// 点击行时，找到这组的原始数据
const handleAccuracyRowClick = (row: any) => {
  const params = {
    ypIndex: row.ypIndex,
    widIndex: row.widIndex,
    thkIndex: row.thkIndex
  };
  handleRowClick(params);
};

onMounted(() => {
  console.log('组件挂载完成'); // 添加调试日志

  // 调用classStatistics接口查看数据
  const testClassStatistics = async () => {
    try {
      const params = {
        pageIndex: 1, // 固定为1，因为只获取一次
        pageSize: 1000 // 获取所有数据
      };
      console.log('调用classStatistics接口，参数:', params);
      const res = await rollingSimulationApi.classStatistics(params);
      console.log('classStatistics接口返回数据:', res);
    } catch (error: any) {
      console.error('classStatistics接口调用失败:', error);
    }
  };

  testClassStatistics();

  // 获取两个列表的数据
  fetchSteelGradeData();
  fetchTableData();
});

// 弹窗关闭时清理图表
const handleDialogClose = () => {
  if (zpChart) {
    zpChart.dispose();
    zpChart = null;
  }
  selectedRow.value = null;
};
</script>
<style scoped lang="less">
// 使用导入的样式文件，这里可以添加额外的自定义样式

.tables-container {
  display: flex;
  gap: 30px;
  margin-bottom: 20px;
  width: 100%;
  align-items: flex-start;
}

.steel-grade-container {
  flex: 0 0 340px; // 减小固定宽度
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 16px;
  height: 600px; // 固定高度
  display: flex;
  flex-direction: column;
}

.accuracy-container {
  flex: 1; // 占据剩余空间
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 16px;
  height: 600px; // 固定高度，与左边一致
  display: flex;
  flex-direction: column;
  overflow-x: auto; // 如果内容过宽，允许横向滚动
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 16px;
  padding: 8px 0;
  border-bottom: 3px solid #409eff;
  position: relative;
  flex-shrink: 0; // 防止标题被压缩

  &::after {
    content: '';
    position: absolute;
    bottom: -3px;
    left: 0;
    width: 60px;
    height: 3px;
    background: #67c23a;
  }
}

.table-container-main {
  margin-top: 10px;
  flex: 1; // 占据剩余空间
  overflow: hidden; // 防止内容溢出
  display: flex;
  flex-direction: column;
}

// 确保表格不会超出容器宽度
.accuracy-container .el-table {
  width: 100%;
  max-width: 100%;
  flex: 1; // 表格占据剩余空间
}

// 调整表格列宽度，避免超出屏幕
.accuracy-container .el-table-column {
  min-width: 60px; // 设置最小宽度
}

// 美化表格样式
.el-table {
  border-radius: 6px;
  overflow: hidden;
  height: 100%; // 表格占满容器高度

  .el-table__header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

    th {
      background: transparent !important;
      color: #fff !important;
      font-weight: 600;
    }
  }

  .el-table__body {
    tr:hover {
      background-color: #f5f7fa;
    }
  }
}

// 钢种信息表格特殊样式
.steel-grade-container .el-table {
  .el-table__header {
    background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
  }
}

// 精度统计表格特殊样式
.accuracy-container .el-table {
  .el-table__header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .tables-container {
    flex-direction: column;
    gap: 20px;
  }

  .steel-grade-container {
    flex: none;
    width: 100%;
    height: 400px; // 在小屏幕上减小高度
  }

  .accuracy-container {
    flex: none;
    width: 100%;
    height: 400px; // 在小屏幕上减小高度
  }
}
</style>
